var express = require('express');
const {execCommand, getCurrentTime, readResultLines} = require("../utils/utils");
var router = express.Router();

//=======================================和命令行相关的sse连接=======================================
router.get('/events', async function (req, res, next) {
  res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  //'git checkout .'
  //D:\WorkPlace\Git_Project
  let commandList = ['pwd', 'cd D:\\WorkPlace\\Vue_Project1\\AgentManage', 'git branch', 'git pull', 'npm run build:pro']
  //循环执行多个命令
  for (let i = 0; i < commandList.length; i++) {
    let commandItem = commandList[i]
    try {
      res.write(`data:${getCurrentTime()} #### ${commandItem}\n\n`)
      let result = await execCommand(commandItem)
      let {stdout, error, stderr} = result
      console.log("result====", i, result)
      readResultLines(stdout).forEach(item => res.write(`data:${getCurrentTime(true)}===== ${item}\n\n`))
    } catch (e) {
      readResultLines(e.message).forEach(item => res.write(`data:${getCurrentTime(true)}===== ${item}\n\n`))
      return
    }
  }
  res.write(`data:end\n\n`)
  res.end()
});

//=======================================sse结合的网络请求=======================================
let setTask = null

router.get('/eventsTest', function (req, res, next) {
  res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  let num = 0
  let strArr = ['所有人,都得死!', '犯我德邦者,虽远必诛!', '吾所成之事,不可逆也!', '一点寒芒先到,随后枪出如龙!', '我的剑就是你的剑!', '刀下生,刀下死!']
  setTask = setInterval(() => {
    res.write(`data:${strArr[num]}\n\n`)
    num++
    if (num > 5) {
      res.write(`data:end\n\n`)
      res.end()
      clearInterval(setTask)
      setTask = null
    }
  }, 2000)
});

module.exports = router;
